package com.jstyle.jclifexd.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.haibin.calendarview.Calendar;
import com.haibin.calendarview.CalendarLayout;
import com.haibin.calendarview.CalendarView;
import com.jstyle.jclifexd.R;
import com.jstyle.jclifexd.activity.BodyFatTipsActivity;
import com.jstyle.jclifexd.adapter.BodyFatAdapter;
import com.jstyle.jclifexd.adapter.RecyclerViewBaseAdapter;
import com.jstyle.jclifexd.daoManager.BodyFatDaoManager;
import com.jstyle.jclifexd.model.BodyFatData;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import butterknife.BindArray;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * {@link OnFragmentInteractionListener} interface
 * to handle interaction events.
 * Use the {@link BodyFatFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class BodyFatFragment extends BaseFragment implements RecyclerViewBaseAdapter.OnItemClickListener {
    // TODO: Rename parameter arguments, choose names that match
    // the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    @BindView(R.id.bt_ecghistory_date)
    Button btEcghistoryDate;
    @BindView(R.id.iv_date)
    ImageView ivDate;
    @BindView(R.id.ll_date)
    LinearLayout llDate;
    @BindView(R.id.CalendarView_sleep_Month)
    CalendarView CalendarViewSleepMonth;
    @BindView(R.id.bt_title)
    Button btTitle;
    @BindView(R.id.button5)
    Button bt_bc;
    @BindView(R.id.tv_bmiValue)
    TextView tvBmiValue;
    @BindView(R.id.tv_bmi)
    TextView tvBmi;
    @BindView(R.id.view_1)
    View view1;
    @BindView(R.id.tv_bodyAgeValue)
    TextView tvBodyAgeValue;
    @BindView(R.id.tv_bodyAge)
    TextView tvBodyAge;
    @BindView(R.id.view_2)
    View view2;
    @BindView(R.id.tv_bodyTypeValue)
    TextView tvBodyTypeValue;
    @BindView(R.id.tv_bodyType)
    TextView tvBodyType;
    @BindView(R.id.bt_bodyfat_percent)
    TextView btBodyfatPercent;
    @BindView(R.id.RecyclerView_bodyFat)
    RecyclerView RecyclerViewBodyFat;
    @BindView(R.id.ScrollView)
    NestedScrollView ScrollView;
    @BindView(R.id.CalendarLayout)
    com.haibin.calendarview.CalendarLayout CalendarLayout;
    Unbinder unbinder;
    @BindArray(R.array.bodyFat_array)
    String[] bodyFatArray;
    @BindView(R.id.tv_bodyFat_date)
    TextView tvBodyFatDate;
    @BindView(R.id.iv_bc_level)
    ImageView ivBcLevel;
    @BindArray(R.array.bodyfat_tips)
    String[]bodyFatTips;
    // TODO: Rename and change types of parameters
    private String mParam1;
    private String mParam2;

    private OnFragmentInteractionListener mListener;
    private BodyFatAdapter bodyFatAdapter;

    public BodyFatFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @param param1 Parameter 1.
     * @param param2 Parameter 2.
     * @return A new instance of fragment BodyFatFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static BodyFatFragment newInstance(String param1, String param2) {
        BodyFatFragment fragment = new BodyFatFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PARAM1, param1);
        args.putString(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            mParam1 = getArguments().getString(ARG_PARAM1);
            mParam2 = getArguments().getString(ARG_PARAM2);
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            CalendarViewSleepMonth.scrollToCurrent();
        }
    }

    private static final String TAG = "BodyFatFragment";

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_body_fat, container, false);
        unbinder = ButterKnife.bind(this, view);
        init();
        return view;
    }

    private void init() {
        bodyFatAdapter = new BodyFatAdapter(Arrays.asList(bodyFatArray));
        bodyFatAdapter.setOnItemClickListener(this);
        RecyclerViewBodyFat.setAdapter(bodyFatAdapter);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext()) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        RecyclerViewBodyFat.setLayoutManager(linearLayoutManager);
        CalendarViewSleepMonth.setOnDateSelectedListener(new CalendarView.OnDateSelectedListener() {
            @Override
            public void onDateSelected(Calendar calendar, boolean isClick) {
                Log.i(TAG, "onDateSelected: " + isClick);
                String date = calendar.getYear() + "." + String.format("%02d", calendar.getMonth()) + "." + String.format("%02d", calendar.getDay());
                btEcghistoryDate.setText(date);
                findData(date);
            }
        });
        CalendarViewSleepMonth.setOnViewChangeListener(new CalendarView.OnViewChangeListener() {
            @Override
            public void onViewChange(boolean isMonthView) {
                ivDate.setRotation(isMonthView?0:180);
            }
        });
    }

    private void findData(String date) {
        List<BodyFatData> bodyFatDataList = BodyFatDaoManager.queryData(date.substring(2));
        String age = "--";
        String bmi = "--";
        String bc = "--";
        String bfp = "--";
        String bw = "--";
        String slm = "--";
        String bmc = "--";
        String pp = "--";
        String bmr = "--";
        String vfr = "--";
        String mc = "--";
        String bfc = "--";
        String dataDate = "--";
        if (bodyFatDataList != null && bodyFatDataList.size() != 0) {
            BodyFatData bodyFatData = bodyFatDataList.get(0);
            dataDate = bodyFatData.getDate().split(" ")[1];
            age = bodyFatData.getBody_age();
            bmi = bodyFatData.getBmi();
            bc = bodyFatData.getSbc();
            bfp = bodyFatData.getBfp() + " %";
            bw = bodyFatData.getBwp() + " %";
            slm = bodyFatData.getSlm() + getString(R.string.kg);
            bmc = bodyFatData.getBmc() + getString(R.string.kg);
            pp = bodyFatData.getPp() + " %";
            bmr = bodyFatData.getBmr() + getString(R.string.cal_laber);
            vfr = bodyFatData.getVfr();
            mc = bodyFatData.getMc() + getString(R.string.kg);
            bfc = bodyFatData.getFc() + getString(R.string.kg);
        }
        tvBmiValue.setText(bmi);
        tvBodyAgeValue.setText(age);
        bt_bc.setText(bc);
        btBodyfatPercent.setText(bfp);
        tvBodyFatDate.setText(dataDate);
        List<String> contentBodyFat = new ArrayList<>();
        contentBodyFat.add(bw);
        contentBodyFat.add(slm);
        contentBodyFat.add(bmc);
        contentBodyFat.add(pp);
        contentBodyFat.add(bmr);
        contentBodyFat.add(vfr);
        contentBodyFat.add(mc);
        contentBodyFat.add(bfc);
        bodyFatAdapter.setContentList(contentBodyFat);
        showBodyFatLevel(bc);
        showBmiLevel(bmi);
    }

    private void showBodyFatLevel(String bcString) {
        if ("--".equals(bcString)) {
            ivBcLevel.setImageDrawable(new ColorDrawable(Color.TRANSPARENT));
        } else {
            int score = Integer.valueOf(bcString);
            if (score < 60) {
                ivBcLevel.setImageResource(R.drawable.body_fat_arrow_down);
            } else if (score > 75) {
                ivBcLevel.setImageResource(R.drawable.body_fat_arrow_up);
            } else {
                ivBcLevel.setImageDrawable(new ColorDrawable(Color.TRANSPARENT));
            }
        }


    }

    private void showBmiLevel(String bmiString) {
        int id = 0;
        if ("--".equals(bmiString)) {
            tvBmiValue.setCompoundDrawables(null, null, null, null);
            return;
        } else {
            float score = Float.valueOf(bmiString);
            if (score < 18.5) {
                id = R.drawable.body_fat_arrow_down;
            } else if (score > 30) {
                id = R.drawable.body_fat_arrow_up;
            }
        }
        if (id == 0) {
            tvBmiValue.setCompoundDrawables(null, null, null, null);
            return;
        }
        Drawable drawable = getContext().getResources().getDrawable(id);
        if (drawable != null) {
            drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            tvBmiValue.setCompoundDrawables(null, null, drawable, null);
        }

    }


    // TODO: Rename method, update argument and hook method into UI event
    public void onButtonPressed(Uri uri) {
        if (mListener != null) {
            mListener.onFragmentInteraction(uri);
        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
//        if (context instanceof OnFragmentInteractionListener) {
//            mListener = (OnFragmentInteractionListener) context;
//        } else {
//            throw new RuntimeException(context.toString()
//                    + " must implement OnFragmentInteractionListener");
//        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.ll_date,R.id.tv_bodyFat,R.id.tv_bmi,R.id.tv_bodyAge,R.id.tv_bodyType})
    public void onViewClicked(View view) {
        switch (view.getId()){
            case R.id.ll_date:
                if (CalendarLayout.isExpand()) {
                    CalendarLayout.shrink();

                } else {

                    ScrollView.fling(0);
                    ScrollView.smoothScrollTo(0, 0);
                    CalendarLayout.expand();
                }
                break;
            case R.id.tv_bodyFat:
                toBodyFatTips("bf",((TextView)view).getText().toString());
                break;
            case R.id.tv_bmi:
                toBodyFatTips("bmi",((TextView)view).getText().toString());
                break;
            case R.id.tv_bodyAge:
                toBodyFatTips("ba",((TextView)view).getText().toString());
                break;
            case R.id.tv_bodyType:
                toBodyFatTips("sbc",((TextView)view).getText().toString());
                break;
        }

    }

    @Override
    public void onItemClick(int position) {
        toBodyFatTips(bodyFatTips[position],bodyFatArray[position]);
    }
    private String baseUrl="http://jstyle.jointcorp.com/app/";
    private void toBodyFatTips(String type,String title){
        Locale locale = getResources().getConfiguration().locale;
        String language = locale.getLanguage();
        String languageType=language.equals("zh")?"zh_CN/":"en/";
        String url=baseUrl+languageType+type+".html";
        Intent intent = new Intent(getActivity(), BodyFatTipsActivity.class);
        intent.putExtra(BodyFatTipsActivity.KEY_BodyFatUrl,url);
        intent.putExtra(BodyFatTipsActivity.KEY_Title,title);
        startActivity(intent);

    }
    /**
     * This interface must be implemented by activities that contain this
     * fragment to allow an interaction in this fragment to be communicated
     * to the activity and potentially other fragments contained in that
     * activity.
     * <p>
     * See the Android Training lesson <a href=
     * "http://developer.android.com/training/basics/fragments/communicating.html"
     * >Communicating with Other Fragments</a> for more information.
     */
    public interface OnFragmentInteractionListener {
        // TODO: Update argument type and name
        void onFragmentInteraction(Uri uri);
    }
}
